package com.baicaoyuan.web.controller;

import com.alibaba.fastjson.JSON;
import com.baicaoyuan.web.common.CheckPower;
import com.baicaoyuan.web.common.LogUtil;
import com.baicaoyuan.web.common.Status;
import com.baicaoyuan.web.common.StringUtils;
import com.baicaoyuan.web.common.annotation.MemberAccess;
import com.baicaoyuan.web.common.excel.ExcelUtils;
import com.baicaoyuan.web.common.excel.ProfitInput;
import com.baicaoyuan.web.common.exception.StateMessage;
import com.baicaoyuan.web.enums.BusinessTypeEnum;
import com.baicaoyuan.web.model.JzzBusinessDO;
import com.baicaoyuan.web.model.UserDO;
import com.baicaoyuan.web.request.BaseRequest;
import com.baicaoyuan.web.request.br.*;
import com.baicaoyuan.web.response.*;
import com.baicaoyuan.web.service.JzzBusinessService;
import com.baicaoyuan.web.service.JzzService;
import com.baicaoyuan.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 功能描述：
 *
 * @author 罗富祥
 * 创建时间： 2018/1/4
 */
@Api(value = "jzz Controller", tags = {"jzz操作接口"})
@RestController
@RequestMapping(value = "/jzz")
public class JzzController {

    @Autowired
    JzzService jzzService;

    @Autowired
    UserService userService;

    @Autowired
    JzzBusinessService jzzBusinessService;

    @Autowired
    CheckPower checkPower;

    @ApiOperation(value = "后台-excel金种子利润导入模版（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/profitInput/periodNos/profit/excel/import", method = RequestMethod.POST)
    @ResponseBody
    public Status importExcelOfJzzProfitInput(@RequestParam(value = "uploadFile") MultipartFile file,
                                              @RequestParam(value = "token") String token,
                                              @RequestParam(value = "userId") Long userId) {
        try {

            checkPower(token, userId);

            boolean r = false;
            long t1 = System.currentTimeMillis();
            List<ProfitInput> list = ExcelUtils.readExcel("", ProfitInput.class, file);
            long t2 = System.currentTimeMillis();
            System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
            list.forEach(
                    b -> System.out.println(JSON.toJSONString(b))
            );
            r = jzzService.saveProfitInput(list, userId);


            Status result = new Status(r ? StateMessage.SUCCESS : StateMessage.FAILED);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    private void checkPower(String token, Long userId) throws Exception {
        if (userService.checkToken(userId, token)) {
            UserDO userDO = userService.findOne(userId);

            if ("1".equals(userDO.getStatus()) && "3".equals(userDO.getWebAdmin())) {

            } else {
                throw new Exception("无权限");
            }
        } else {
            throw new Exception("无权限");
        }
    }

    @ApiOperation(value = "后台-获取未进入分润的excel期号（excel 有一列期号标识，用于审核，撤销）（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/profitInput/periodNos/list", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status getPeriodNos(@RequestBody BStatusRequest bRequest) {
        try {
            checkPower(bRequest.getToken(), bRequest.getUserId());
            List<String> list = jzzService.getDistinctPeriodNo(bRequest.getStatus());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("periodNos", list);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "后台-审核通过分润后 进入分润(状态码：1 进入分润，默认 0)（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/profitInput/periodNos/check", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status checkProfit(@RequestBody BProfitInputPeriodNosRequest bRequest) {
        try {
            checkPower(bRequest.getToken(), bRequest.getUserId());
            jzzService.checkProfit(bRequest.getPeriodNos(), 1);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "后台-撤销分润(状态码：9 撤销分润)（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/profitInput/periodNos/revert", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status revertProfit(@RequestBody BProfitInputPeriodNosRequest bRequest) {
        try {
            checkPower(bRequest.getToken(), bRequest.getUserId());
            jzzService.revertProfit(bRequest.getPeriodNos(), 9);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "后台-分润输入列表页-分页(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/profitInput/list", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status getProfitInputs(@RequestBody BJzzProfitInputPageRequest request) {
        try {
            checkPower(request.getToken(), request.getUserId());

            List<JzzProfitInputResponse> jzzProfitInput =
                    jzzService.getJzzProfitInput(request.getStatus(),
                            StringUtils.plusPercent(request.getPeriodNo()),
                            StringUtils.plusPercent(request.getSerialNumber()),
                            request.getPage(), request.getSize());
            Integer count = jzzService.getCountOfAll(request.getStatus(),
                    StringUtils.plusPercent(request.getPeriodNo()),
                    StringUtils.plusPercent(request.getSerialNumber()));
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("jzzProfitInput", jzzProfitInput);
            result.setData("totalCount", count);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }


    @ApiOperation(value = "交易-列表", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/business", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status business(@RequestBody BJzzBusinessPageRequest request) {
        try {
            JzzBusinessResponse response = jzzBusinessService.getBusiness(BusinessTypeEnum.acquire(request.getType()), request.getPage(), request.getSize());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("business", response);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-成交列表", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/doneBusiness", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status doneBusiness(@RequestBody BJzzDoneBusinessPageRequest request) {
        try {
            JzzDoneBusinessResponse response = jzzBusinessService.getDoneBusiness(request.getUserId(), request.getPage(), request.getSize());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("business", response);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }


    @ApiOperation(value = "交易-详情", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/business/details", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status details(@RequestBody BJzzId bRequest) {
        try {
            JzzBusinessDetailsResponse r;
            r = jzzBusinessService.details(bRequest.getId());
            r.setSourceUser(userService.getSimpleUser(r.getSourceUserId()));
            r.setTargetUser(userService.getSimpleUser(r.getTargetUserId()));
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-发布卖金子需求", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/sale", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status sale(@RequestBody BJzzSale bRequest) {
        try {
            boolean r = jzzBusinessService.createSale(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-我要买金子", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/toBuy", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status toBuy(@RequestBody BJzzToBuy bRequest) {
        try {
            JzzBusinessDO r;
            r = jzzBusinessService.toBuy(bRequest, bRequest.getUserId());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-我要上传打款凭证", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/toBuyUploadVoucher", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status toBuyUploadVoucher(@RequestBody BJzzToBuyUploadVoucher bRequest) {
        try {
            boolean r;
            r = jzzBusinessService.toBuyUploadVoucher(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-发布买金子需求", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/buy", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status buy(@RequestBody BJzzBuy bRequest) {
        try {
            boolean r = jzzBusinessService.createBuy(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-我要卖金子", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/toSale", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status toSale(@RequestBody BJzzToSale bRequest) {
        try {
            boolean r;
            r = jzzBusinessService.toSale(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-最后一步：根据码核对交易", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/checkDone", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status checkDone(@RequestBody BJzzBuySaleCheck bRequest) {
        try {
            jzzBusinessService.checkDone(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-最后第二步：发送码", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/sendMa", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status sendMa(@RequestBody BJzzToBuy bRequest) {
        try {
            jzzBusinessService.sendMa(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-我的买列表", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/myBuyBusiness", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status myBuyBusiness(@RequestBody BaseRequest bRequest) {
        try {
            List<JzzBusinessMyResponse> r;
            r = jzzBusinessService.getBuyBusinessByUserId(bRequest.getUserId());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-我的卖列表", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/mySaleBusiness", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status mySaleBusiness(@RequestBody BaseRequest bRequest) {
        try {
            List<JzzBusinessMyResponse> r;
            r = jzzBusinessService.getSaleBusinessByUserId(bRequest.getUserId());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-卖方取消", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/saleCancel", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status saleCancel(@RequestBody BJzzToBuy bRequest) {
        try {
            boolean r;
            r = jzzBusinessService.saleCancel(bRequest.getUserId(), bRequest.getId());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-买方取消", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/buyCancel", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status buyCancel(@RequestBody BJzzToBuy bRequest) {
        try {
            boolean r;
            r = jzzBusinessService.buyCancel(bRequest.getUserId(), bRequest.getId());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }


    @ApiOperation(value = "交易-列表(后台)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/admin/business", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status adminBusiness(@RequestBody BJzzAdminBusinessPageRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());

            JzzDoneBusinessResponse response = jzzBusinessService.getAdminBusiness(request.getStatus(), request.getPage(), request.getSize());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("business", response);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "交易-强制发送码（后台）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/admin/sendMa", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status adminSendMa(@RequestBody BJzzToBuy bRequest) {
        try {
            checkPower.checkPower(bRequest.getToken(), bRequest.getId());
            checkPower.checkClient(bRequest.getClient());

            jzzBusinessService.adminSendMa(bRequest);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }
}
